package com.lw.sbdemo2.web;

import com.lw.sbdemo2.common.base.BaseController;
import com.lw.sbdemo2.common.exception.ApiException;
import com.lw.sbdemo2.common.exception.ResponseCodeEnum;
import com.lw.sbdemo2.common.vo.ResultModel;
import com.lw.sbdemo2.common.web.anno.ResultController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2017</p>
 * <p>公司: 智业软件</p>
 *
 * @author: linqunyuan
 * @createTime 2019/4/17
 */
@ResultController
@Api(description = "FileUploadController", tags = {"文件上传服务"})
@RequestMapping(value = "/file")
@Slf4j
public class FileUploadController extends BaseController {

    @Value(value = "${info.app.uploadFilePath}")
    private String filePath;

    @Value(value = "${info.app.baseUrl}")
    private String baseUrl;

    final static String videoAddress = "/root/exam/server/video/";

    @ApiOperation(value = "单文件上传")
    @ApiResponse(code = 200, message ="上传成功返回url", response = ResultModel.class)
    @PostMapping("/upload")
    public ResultModel fileUpload(HttpServletRequest request, String termName, String unitName) {

        //重命名上传后的文件名
        String fileName = UUID.randomUUID().toString();

        try {
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (commonsMultipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multipartHttpServletRequest.getFileNames();
                while (iter.hasNext()) {
                    //记录上传过程起始时的时间，用来计算上传时间
                    long start = System.currentTimeMillis();

                    //取得上传文件
                    MultipartFile file = multipartHttpServletRequest.getFile(iter.next());
                    if (file != null) {
                        String name = file.getOriginalFilename();
                        String suffix = name.substring(name.lastIndexOf("."));
                        fileName = fileName + suffix;
                        File localFile = new File(videoAddress + fileName);
                        File fileParent = localFile.getParentFile();
                        if (!fileParent.exists()) {
                            fileParent.mkdirs();
                        }
                        try {
                            file.transferTo(localFile);
                        } catch (IOException e) {
                            throw new ApiException("上传文件失败");
                        }

                    }
                    //记录上传该文件后的时间
                    long end = System.currentTimeMillis();
                    log.info("耗时：" + (end - start) + "毫秒");
                }
            }
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return ResultModel.fail(ResponseCodeEnum.EX_PARAM, e.getMessage());
        }
        return ResultModel.success(baseUrl+fileName);
    }
    @ApiOperation(value = "单文件上传")
    @ApiResponse(code = 200, message ="上传成功返回url", response = ResultModel.class)
    @PostMapping("/fileUploadVideo")
    public ResultModel fileUploadVideo(HttpServletRequest request) {

        //重命名上传后的文件名
        String fileName = UUID.randomUUID().toString();

        try {
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (commonsMultipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multipartHttpServletRequest.getFileNames();
                while (iter.hasNext()) {
                    //记录上传过程起始时的时间，用来计算上传时间
                    long start = System.currentTimeMillis();

                    //取得上传文件
                    MultipartFile file = multipartHttpServletRequest.getFile(iter.next());
                    if (file != null) {
                        String name = file.getOriginalFilename();
                        String suffix = name.substring(name.lastIndexOf("."));
                        fileName = fileName + suffix;
                        File localFile = new File(filePath + fileName);
                        File fileParent = localFile.getParentFile();
                        if (!fileParent.exists()) {
                            fileParent.mkdirs();
                        }
                        try {
                            file.transferTo(localFile);
                        } catch (IOException e) {
                            throw new ApiException("上传文件失败");
                        }

                    }
                    //记录上传该文件后的时间
                    long end = System.currentTimeMillis();
                    log.info("耗时：" + (end - start) + "毫秒");
                }
            }
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return ResultModel.fail(ResponseCodeEnum.EX_PARAM, e.getMessage());
        }
        return ResultModel.success(baseUrl+fileName);
    }


}
